using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace TST.SharePointObjects.SecurityBluePrint.Timerjobs
{
    public class CreateBluePrintsTimerJob : SPJobDefinition
    {
        private string _ProfileProperty = string.Empty;
        private string _SharedServicesProvider = string.Empty;

        public CreateBluePrintsTimerJob()
            : base()
        {
            this.Title = Globals.SECURITYBLUEPRINTJOBNAME;
        }

        public CreateBluePrintsTimerJob(string jobName,
                        SPService service,
                        SPServer server,
                        SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
            this.Title = Globals.SECURITYBLUEPRINTJOBNAME;
        }

        public CreateBluePrintsTimerJob(string jobName,
                            SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.Job)
        {
            this.Title = Globals.SECURITYBLUEPRINTJOBNAME;
        }

        public override void Execute(Guid contentDbId)
        {
            Trace.WriteLine("Start " + Globals.SECURITYBLUEPRINTJOBNAME);
            SPSiteCollection sites = WebApplication.Sites;
            foreach (SPSite site in sites)
            {
                try
                {
                    using (SPWeb root = site.RootWeb)
                    {
                        Trace.WriteLine(String.Format("Create blueprint for rootweb {0}.", root.Url));
                        String url = String.Empty;
                        if (Properties[Globals.SECURITYBLUEPRINTLIBRARYSITEURL] != null)
                        {
                            url = Properties[Globals.SECURITYBLUEPRINTLIBRARYSITEURL].ToString();
                        }
                        SecurityBluePrint bluePrint = new SecurityBluePrint(url);
                        if (Properties[Globals.SECURITYBLUEPRINTENDPOINTS] != null)
                        {
                            bluePrint.EndPoints = Properties[Globals.SECURITYBLUEPRINTENDPOINTS].ToString();
                        }
                        bluePrint.Run(root);
                    }
                }
                finally
                {
                    if (site != null)
                    {
                        site.Dispose();
                    }
                }
            }
        }

    }
}
